/**
* All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
*
* MmsProductFloorPriceInfoService
* 产品红线价格信息表
*
* 修改纪录
* 2022-05-24 版本：1.0 hudeyong 创建。
* @version 版本：1.0
* @author 作者：hudeyong
* 创建日期：2022-05-24
*/
package com.topscomm.mms.service.impl;

import cn.hutool.core.convert.Convert;
import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.service.impl.BaseChangeLogService;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboMessageAppEntity;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.cbo.pojo.CboSysParamEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.cbo.service.ICboRoleService;
import com.topscomm.cbo.service.ICboUserRoleService;
import com.topscomm.cbo.service.impl.CboSysParamService;
import com.topscomm.mms.pojo.MmsProductBaseInfoEntity;
import com.topscomm.mms.pojo.MmsProductFloorPriceInfoEntity;
import com.topscomm.mms.pojo.MmsProductFloorPriceInfoHisEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.RedisMmsStore;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mms.service.IMmsProductFloorPriceInfoService;
import com.topscomm.mms.service.impl.auto.MmsProductFloorPriceInfoServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "mmsProductFloorPriceInfoService")
@Scope(value = "singleton")
public class MmsProductFloorPriceInfoService extends MmsProductFloorPriceInfoServiceAuto implements IMmsProductFloorPriceInfoService {
    @Autowired
    CboSysParamService cboSysParamService;
    @Autowired
    protected ICboMessageAppService cboMessageAppService;
    @Autowired
    protected ICboMessageSysService cboMessageSysService;
    @Autowired
    protected ICboRoleService cboRoleService;
    @Autowired
    protected BaseChangeLogService baseChangeLogService;
    @Autowired
    protected MmsProductFloorPriceInfoHisService mmsProductFloorPriceInfoHisService;
    @Autowired
    private RedisMmsStore redisMmscodeStore;

    @Override
    protected void beforeInsert(BasicEntity entity) throws ServiceException {
        super.beforeInsert(entity);
        //查询当前产品下是否存在当前新增的小类
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0}='{1}' ", MmsProductFloorPriceInfoEntity.FieldProductid, entity.getValue(MmsProductFloorPriceInfoEntity.FieldProductid));
        sql.appendSingle(" and {0}='{1}' ", MmsProductFloorPriceInfoEntity.FieldCatalog3, entity.getValue(MmsProductFloorPriceInfoEntity.FieldCatalog3));
        int count = this.getCount(sql.toString());
        if(count>0) {
            throw new ServiceException("当前产品下已存在当前新增的小类");
        }
    }
    @Override
    protected void afterInsert(BasicEntity entity) throws ServiceException {
        super.afterInsert(entity);
        //新增默认未启用，未发布
        entity.setValue(MmsProductFloorPriceInfoEntity.FieldEnabled, 0);
        entity.setValue(MmsProductFloorPriceInfoEntity.FieldPublishstate, "0");
        this.updateEntity(entity);
        this.addValueToRedis(MmsProductBaseInfoEntity.tableName);
    }

    @Override
    protected void updateBefore(Map<String, Object> map) throws ServiceException {
        super.updateAfter(map);
        //查询当前产品下是否存在当前新增的小类
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0}='{1}' ", MmsProductFloorPriceInfoEntity.FieldProductid, map.get(MmsProductFloorPriceInfoEntity.FieldProductid));
        sql.appendSingle(" and {0}='{1}' ", MmsProductFloorPriceInfoEntity.FieldCatalog3, map.get(MmsProductFloorPriceInfoEntity.FieldCatalog3));
        sql.appendSingle(" and {0}!= {1} ", MmsProductFloorPriceInfoEntity.FieldId, map.get(MmsProductFloorPriceInfoEntity.FieldId));
        int count = this.getCount(sql.toString());
        if(count>0) {
            throw new ServiceException("当前产品下已存在当前修改的小类");
        }
        MmsProductFloorPriceInfoEntity oldInfo = this.queryById(ConvertUtil.convertToString(map.get("id")));
        if (oldInfo.getEnabled() == 1 && ConvertUtil.convertToInt(map.get("enabled")) == 0) {
            redisMmscodeStore.removeKey("productBaseInfoCatalog3List");
        }
        // 根据角色获取修改红线价格的人
        List<Map<String,Object>> users = cboRoleService.selectExecute(" select id,code,name " +
                " from cbouser " +
                " where id in (select userid " +
                " from CBOUSERROLE " +
                " where ROLEID = (select id from CBOROLE where code = 'BusinessDeptHeader')) ");
        boolean permissionUser = users.stream().anyMatch(item -> item.get("code").equals(getSessionUserBean().getUser().getCode()));
        //没红线管理员无法更新红线价格
        if(!permissionUser) {
            map.remove(MmsProductFloorPriceInfoEntity.FieldFloorprice);
        }
        //发布的小类更新价格时记录变更历史
        if("1".equals(ConvertUtil.convertToString(map.get("publishstate"))) && permissionUser) {
            Map<String, Object> oldMap = queryMapById(ConvertUtil.convertToString(map.get("id")));
            Map<String, Object> param = new HashMap<>();
            param.put("sourceid", oldMap.get("id"));
            param.put("sourcetype", MmsProductFloorPriceInfoEntity.tableName);
            param.put("oldmap", oldMap);
            param.put("newmap", map);
            param.put("baselogoperatetype", BaseSystemConst.BaseLogOperateTypeEnum.Edit);
            param.put("topsourcetype", MmsProductFloorPriceInfoEntity.tableName);
            param.put("topsourceid", oldMap.get("id"));
            String newVersion = baseChangeLogService.insertChangeLog(param);
            //newVersion不为空存在更新价格
            if (!StringUtil.isEmpty(newVersion)) {
                // 保存历史表信息
                MmsProductFloorPriceInfoHisEntity hisEntity = new MmsProductFloorPriceInfoHisEntity();
                hisEntity.convertFromMap(oldMap);
                hisEntity.setId(0);
                hisEntity.setFloorpriceid(ConvertUtil.convertToLong(oldMap.get("id")));
                mmsProductFloorPriceInfoHisService.insert(hisEntity);
            }
        }
    }


    /**
     * @description: 发布产品
     * @param id
     * @return void
     * @author: wangxinhua
     * @date: 2022/6/20 10:41
     * @modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publishProduct(String id) {
        MmsProductFloorPriceInfoEntity productFloorPriceInfoEntity = this.queryById(id);
        if(productFloorPriceInfoEntity == null) {
            throw new ServiceException("产品信息不存在，无法发布！");
        }
        Map<String, Object> mapInfo = productFloorPriceInfoEntity.convertToMap();
        DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
        this.setDispFields(mapInfo, datacodeCache);
        //给红线价格管理员发送消息
        List<CboSysParamEntity> title = cboSysParamService.queryByWhere(" code = 'MMSProductPublishNoticeTitle' ");
        List<CboSysParamEntity> contents = cboSysParamService.queryByWhere(" code = 'MMSProductPublishNoticeMsg' ");
        if (contents.size() <= 0) {
            throw new ServiceException("发送模板未配置！");
        }
        if (title.size() <= 0) {
            throw new ServiceException("发送标题未配置！");
        }
        // 获取收件人,根据角色获取
        List<Map<String,Object>> users = cboRoleService.selectExecute(" select id,code,name " +
                " from cbouser " +
                " where id in (select userid " +
                " from CBOUSERROLE " +
                " where ROLEID = (select id from CBOROLE where code = 'BusinessDeptHeader')) ");

        String sendContent = contents.get(0).getParamvalue()
                .replace("{userinfo}", getSessionUserBean().getUser().getName() + "[" + getSessionUserBean().getUser().getCode() + "]")
                .replace("{productname}", ConvertUtil.convertToString(mapInfo.get("productname")))
                .replace("{productline}", ConvertUtil.convertToString(mapInfo.get("dispproductline")))
                .replace("{catalog1}", ConvertUtil.convertToString(mapInfo.get("dispcatalog1")))
                .replace("{catalog2}", ConvertUtil.convertToString(mapInfo.get("dispcatalog2")))
                .replace("{catalog3}", ConvertUtil.convertToString(mapInfo.get("dispcatalog3")));


        for (Map<String,Object> user : users) {
            //部长本人发布不发送消息
            if(ConvertUtil.convertToString(user.get("code")).equals(getSessionUserBean().getUser().getCode())) {
                continue;
            }
            // 推送
            Map<String, Object> appMap = new HashMap<String, Object>();
            appMap.put("usercode", user.get("code"));
            appMap.put("extendfield1", title.get(0).getParamvalue());
            appMap.put("content", sendContent);
            appMap.put("sourceid", productFloorPriceInfoEntity.getId());
            appMap.put("sourcetype", productFloorPriceInfoEntity.getTableName());
            appMap.put("sendtype", 1);
            // 消息
            Map<String, Object> sysMap = new HashMap<String, Object>();
            sysMap.put("sendercode", getSessionUserBean().getUser().getCode());
            sysMap.put("sendername", getSessionUserBean().getUser().getName());
            sysMap.put("receivercode", user.get("code"));
            sysMap.put("receivername", user.get("name"));
            sysMap.put("subject", title.get(0).getParamvalue());
            sysMap.put("content", sendContent);
            sysMap.put("sourceid", productFloorPriceInfoEntity.getId());
            sysMap.put("sourcetype", productFloorPriceInfoEntity.getTableName());

            cboMessageAppService.insertMap(appMap);
            cboMessageSysService.insertMap(sysMap);
        }
        //更新
        productFloorPriceInfoEntity.setPublishstate("1"); //发布
        productFloorPriceInfoEntity.setEnabled(1); //启用
        this.updateEntity(productFloorPriceInfoEntity);
        //清缓存
        redisMmscodeStore.removeKey("productBaseInfoCatalog3List");
    }
}
